package com.chujian.framework.web.interceptor;

import com.chujian.framework.auth.Accessor;
import com.chujian.framework.auth.AccessorHolder;
import com.chujian.framework.mybatis.IQueryDataAuthLoader;
import com.chujian.framework.mybatis.auth.QueryDataAuth;
import com.chujian.framework.mybatis.auth.QueryDataAuthHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ：chujian
 * @since ：2021-8-12
 * 数据权限拦截器,用于加载查询数据的权限信息
 */
public class ConfigQueryDataAuthHandlerInterceptor implements HandlerInterceptor {

    private IQueryDataAuthLoader queryDataAuthLoader;

    public ConfigQueryDataAuthHandlerInterceptor(IQueryDataAuthLoader queryDataAuthLoader) {
        this.queryDataAuthLoader = queryDataAuthLoader;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Accessor accessor = AccessorHolder.getAccessor();
        if (null != queryDataAuthLoader
                && null != accessor
                && null != accessor.getDynamicAuth()) {
            QueryDataAuth queryDataAuth = queryDataAuthLoader.loadQueryDataAuth(accessor);
            QueryDataAuthHolder.setQueryDataAuth(queryDataAuth);
        } else {
            // 清空权限信息
            QueryDataAuthHolder.setQueryDataAuth(null);
        }
        return true;
    }

}
